package org.dei.dataserver;

import java.io.*;
import java.util.*;
import org.dei.perla.parser.expressions.*;
import org.dei.perla.parser.grammar.*;
import org.dei.perla.parser.statements.Query;
import org.dei.perla.parser.util.PairValue;
import org.dei.perla.rockfall.gui.MainWindow;
import org.dei.perla.rockfall.utils.DatabaseDump;
import org.dei.perla.sys.device.fpc.dspic.DSPicFPC;
import org.dei.perla.sys.environments.ActiveSession;
import org.dei.perla.sys.environments.Environment;
import org.dei.perla.sys.environments.QueryAnalyzer;
import org.dei.perla.sys.environments.SetEnvironment;
import org.dei.perla.sys.query.llqruntime.datacollection.*;


public class DSPicMain {

	private static ArrayList<DSPicFPC> pDSPicFPCList;
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		final String tQueryDirectory = "test" + File.separatorChar + "query" + File.separatorChar + "query1.txt";
		FileInputStream tInputStream = null;
		Query tQuery = null;
		QueryAnalyzer tQA;
		pDSPicFPCList = new ArrayList<DSPicFPC>();
		ArrayList<PairValue<String, ? extends Constant>> pAttributeToSetList = new ArrayList<PairValue<String, ? extends Constant>>();
		
		try {
			tInputStream = new FileInputStream(tQueryDirectory);
		} 
		catch (FileNotFoundException e) {
		
			System.out.println("File not found!");
		}
	
		new Parser(tInputStream);
	
		try {
			
			tQuery = Parser.StatementSequence();
			
		} catch (ParseException e) {
			
			e.printStackTrace();
		}
		
		Server s = new Server(5606);
		s.start();
		
		QueryAnalyzer.registerQuery(tQuery);
		

		while (ActiveSession.getActiveEnvironments().hasNext()) {
			
		Environment tEnv = ActiveSession.getActiveEnvironments().next();	
		if (tEnv instanceof SetEnvironment) 
			{
			
	
			for (ConstantID tID : ((SetEnvironment) tEnv).getSetInformation().getDevicesToSet()){
				DSPicFPC tTempFpc = new DSPicFPC(s.getFpcPipes(tID.getValueInt()), tID.getValueInt());
				pDSPicFPCList.add(tTempFpc);
				Thread dbDump = new Thread(new DatabaseDump(tTempFpc.registerQuery(null)));
				dbDump.start();
			}
			
			// Creazione interfaccia grafica
			javax.swing.SwingUtilities.invokeLater(new Runnable() {
				public void run() {
					MainWindow window = new MainWindow(null);
					window.showGui();
					
					// Aggiungo tutti i DSPic da cui voglio ricevere i dati
					for (DSPicFPC d : pDSPicFPCList) {
						window.addDevice("DSPic", d.registerQuery(null));
					}
				}
			});
			
			for (String tAttributeToSet : ((SetEnvironment) tEnv).getSetInformation().getAttributeToSet().keySet()){
				pAttributeToSetList.add(new PairValue<String, Constant>(tAttributeToSet,((SetEnvironment) tEnv).getSetInformation().getAttributeToSet().get(tAttributeToSet)));
			}
			}
			
		
		}
		
		
		
		
		
		

		for (DSPicFPC tDSPicFPC : pDSPicFPCList) {
			tDSPicFPC.setUpdateAttributes(pAttributeToSetList);
		}
	}
}
